﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;
using Zombie_Demo.Comm;
using Zombie_Demo.Utilities;

namespace Zombie_Demo.Comm
{
    static class Client
    {
        static NetClient client;
        static bool isRunning = false;
        static System.Timers.Timer updateTimer;

        static readonly string serverIP = "127.0.0.1";
        static readonly int port = 13737;

        public static void ClientInit()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("zd_game");
            client = new NetClient(config);

            NetOutgoingMessage outmsg = client.CreateMessage();

            client.Start();

            //Informs server we are about to send login info
            outmsg.Write((byte)Protocols.PacketTypes.LOGIN);
            outmsg.Write("LoginName");

            client.Connect(serverIP, port, outmsg);

            Utilities.Log.AddLogEvent("Client started @ " + serverIP + " at port " + port);

            updateTimer = new System.Timers.Timer(50);
            //When the timer has elapsed, call the "updateTimer_Elapsed" function
            updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);

            WaitForStartingInfo();
            updateTimer.Start();

        }

        static void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //CheckServerMessages();
            //TODO: Update game world
        }

        private static void WaitForStartingInfo()
        {
            bool canStart = false;

            NetIncomingMessage inc;

            while (!canStart)
            {
                if ((inc = client.ReadMessage()) != null)
                {
                    switch (inc.MessageType)
                    {
                        case NetIncomingMessageType.Data:
                            if (inc.ReadByte() == (byte)Protocols.PacketTypes.WORLDSTATE)
                            {
                                //update the worldstate values

                                canStart = true;
                            }
                            break;
                        default:
                            ErrorManager.AddError("Strange message from server: " + inc.ReadString());
                            break;
                    }
                }
            }
        }

        private static void CheckServerMessages()
        {
            //NetIncomingMessage inc;

            //this would be the same as the starting info expect it does not loop, only receaves server data and updates the data it gets, 
            //eg, does not need complete data to run unlike above
        }

        public static void Disconnect()
        {
            client.Disconnect("user-quit");
        }
    }
}
